package com.mti.monitor.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mti.monitor.bean.model.SysDataSourceConfig;
import com.mti.monitor.bean.model.SysMonitorConfig;
import com.mti.monitor.config.DataSourceContextHolder;
import com.mti.monitor.config.DynamicDataSource;
import com.mti.monitor.mapper.SysDataSourceConfigMapper;
import com.mti.monitor.mapper.SysMonitorConfigMapper;
import com.mti.monitor.mapper.SysMonitorErrorLogMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Log4j2
public class StatisticsService {

    @Autowired
    private SysMonitorConfigMapper sysMonitorConfigMapper;
    @Autowired
    private SysMonitorErrorLogMapper sysMonitorErrorLogMapper;
    @Autowired
    private MessageService messageService;

    @Autowired
    private SysDataSourceConfigMapper sysDataSourceConfigMapper;
    @Autowired
    private DynamicDataSource dynamicDataSource;

    /**
     * 数据统计服务
     */
    public void statisticsData(String monitorId) {
        //切换默认数据源
        DataSourceContextHolder.clearDataSourceType();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysMonitorConfig config = sysMonitorConfigMapper.selectById(monitorId);
        if(!config.getUseYn()){
            return;
        }
        log.info("开始进行数据统计任务【{}】", config.getTaskName());
        String queryJson = config.getStaticsSql();
        JSONArray jsonArray = JSON.parseArray(queryJson);
        StringBuffer stringBuffer = new StringBuffer(sdf.format(new Date()) + config.getTaskName() + " : ");
        String sql = "";
        try {

            SysDataSourceConfig dataSource = sysDataSourceConfigMapper.selectById(config.getDataSourceId());
            //创建数据源连接&检查 若存在则不需重新创建
            dynamicDataSource.createDataSourceWithCheck(dataSource);
            //切换到该数据源
            DataSourceContextHolder.setDataSourceType(dataSource.getDataSourceId());

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                String name = json.getString("name");
                sql = json.getString("executeSql");
                int count = sysMonitorErrorLogMapper.queryCountBySql(sql);
                stringBuffer.append(name + " : ");
                stringBuffer.append(count + " 条；");
            }
            //切换默认数据源
            DataSourceContextHolder.clearDataSourceType();
            messageService.sendAlarmMessage(config.getPhoneNumbers(), stringBuffer.toString(), config.getMessageChannel());
            log.info("数据统计任务【{}】统计完成：{}", config.getTaskName(), stringBuffer.toString());
        } catch (Exception e) {
            //切换默认数据源
            DataSourceContextHolder.clearDataSourceType();
            log.error("统计任务【{}】在数据源{}上执行SQL有误:{}", config.getTaskName(), config.getDataSourceId(), sql);
        }


    }
}
